package com.steveproject.parttimeworktree.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.steveproject.parttimeworktree.App;
import com.steveproject.parttimeworktree.R;
import com.steveproject.parttimeworktree.adapter.DailyAdapter;
import com.steveproject.parttimeworktree.adapter.Part2JobAdapter;
import com.steveproject.parttimeworktree.adapter.Part2MsgAdapter;
import com.steveproject.parttimeworktree.adapter.Part2PublicAdapter;
import com.steveproject.parttimeworktree.adapter.ScreenAccountAdapter;
import com.steveproject.parttimeworktree.adapter.ScreenSexAdapter;
import com.steveproject.parttimeworktree.adapter.ScreenWeekAdapter;
import com.steveproject.parttimeworktree.base.BaseFragment;
import com.steveproject.parttimeworktree.customprovider.GridItemDecoration;
import com.steveproject.parttimeworktree.entity.DailyEntity;
import com.steveproject.parttimeworktree.entity.Part2JobEntity;
import com.steveproject.parttimeworktree.entity.Part2MsgEntity;
import com.steveproject.parttimeworktree.entity.PartBaseEntity;
import com.steveproject.parttimeworktree.entity.PartSiftEntity;
import com.steveproject.parttimeworktree.myinterface.DeleteJobs;
import com.steveproject.parttimeworktree.net.MyCallback;
import com.steveproject.parttimeworktree.net.NoValidationTask;
import com.steveproject.parttimeworktree.ui.activity.Part2JobDetailActivity;
import com.steveproject.parttimeworktree.ui.activity.PartCategoriesActivity;
import com.steveproject.parttimeworktree.ui.activity.PartDetailActivity;
import com.steveproject.parttimeworktree.utils.AppConfig;
import com.steveproject.parttimeworktree.utils.NewsToastUtils;
import com.steveproject.parttimeworktree.utils.ScreenUtil;
import com.steveproject.putorefresh.BaseBothListener;
import com.steveproject.putorefresh.PullToBothLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

@SuppressLint("ValidFragment")
public class PartMsgFragment extends BaseFragment {
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerView1)
    RecyclerView recyclerView1;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;

    @BindView(R.id.msg_screen)
    RelativeLayout msg_screen;

    @BindView(R.id.recycle_1)
    RecyclerView recycle_1;
    @BindView(R.id.recycle_2)
    RecyclerView recycle_2;
    @BindView(R.id.recycle_3)
    RecyclerView recycle_3;

    @BindView(R.id.img_screen)
    ImageView imgScreen;


    @BindView(R.id.iv_1)
    RoundedImageView iv_1;
    @BindView(R.id.iv_2)
    RoundedImageView iv_2;
    @BindView(R.id.iv_3)
    RoundedImageView iv_3;
    @BindView(R.id.iv_4)
    RoundedImageView iv_4;
    @BindView(R.id.iv_5)
    RoundedImageView iv_5;

    private ScreenAccountAdapter screenAccountAdapter = null;
    private ScreenSexAdapter screenSexAdapter = null;
    private ScreenWeekAdapter screenWeekAdapter = null;


    private boolean isFirst = true;
    private List<View> views;
    private Part2MsgAdapter part2MsgAdapter = null;
    private List<Part2MsgEntity> list = new ArrayList<>();
    private TextView textView;
    private boolean isShow = false;


    public static int sexSelected = -1;
    public static int accountSelected = -1;
    public static int weekSelected = -1;

    public static boolean isRefresh = true;//默认是下拉刷新
    private int page = 1;


    public PartMsgFragment(TextView tv_bg) {
        this.textView = tv_bg;
    }


    private List<PartSiftEntity> sexArray = new ArrayList<>();
    private List<PartSiftEntity> accountArray = new ArrayList<>();
    private List<PartSiftEntity> weekArray = new ArrayList<>();


    private Part2PublicAdapter part2JobAdapter = null;
    private List<Part2JobEntity> list_jobs = new ArrayList<>();

    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_part2_msg, null);
    }

    @OnClick({R.id.ll_screen, R.id.top_bg, R.id.ll_screen_bg, R.id.tv_reset, R.id.tv_confirm
            , R.id.iv_1, R.id.iv_2, R.id.iv_3, R.id.iv_4, R.id.iv_5})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.ll_screen://筛选按钮
                if (isShow) {//隐藏
                    msg_screen.setVisibility(View.GONE);
                    textView.setVisibility(View.GONE);
                    imgScreen.setImageResource(R.drawable.icon_featured_collapse);
                } else {
                    imgScreen.setImageResource(R.drawable.icon_featured_expand);
                    msg_screen.setVisibility(View.VISIBLE);
                    textView.setVisibility(View.VISIBLE);
                }
                isShow = !isShow;
                break;
            case R.id.top_bg:
                msg_screen.setVisibility(View.GONE);
                textView.setVisibility(View.GONE);
                isShow = !isShow;
                imgScreen.setImageResource(R.drawable.icon_featured_collapse);
                break;
            case R.id.ll_screen_bg://阻止事件
                break;
            case R.id.tv_reset://重置
                sexSelected = -1;
                accountSelected = -1;
                weekSelected = -1;
                screenSexAdapter.notifyDataSetChanged();
                screenWeekAdapter.notifyDataSetChanged();
                screenAccountAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_confirm://进行筛选
                msg_screen.setVisibility(View.GONE);
                textView.setVisibility(View.GONE);
                imgScreen.setImageResource(R.drawable.icon_featured_collapse);
                isRefresh = true;
                page = 1;
                getJobs(isFirst);
                break;
            case R.id.iv_1:
                startActivity(new Intent(getActivity(), Part2JobDetailActivity.class).putExtra("type", "0"));
                break;
            case R.id.iv_2:
                startActivity(new Intent(getActivity(), Part2JobDetailActivity.class).putExtra("type", "1"));
                break;
            case R.id.iv_3:
                startActivity(new Intent(getActivity(), Part2JobDetailActivity.class).putExtra("type", "2"));
                break;
            case R.id.iv_4:
                startActivity(new Intent(getActivity(), Part2JobDetailActivity.class).putExtra("type", "3"));
                break;
            case R.id.iv_5:
                startActivity(new Intent(getActivity(), Part2JobDetailActivity.class).putExtra("type", "4"));
                break;

        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        setListen();
        initScreenView();
        initSelectionRecommendation();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                getJobsRecome();
                getJobs(true);
                initScreenData();
                isFirst = false;
            }
        }
    }


    private void setListen() {
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                msg_screen.setVisibility(View.GONE);
                textView.setVisibility(View.GONE);
                isShow = !isShow;
            }
        });
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                isRefresh = true;
                page = 1;
                getJobs(isFirst);
            }

            @Override
            public void loadMore() {
                isRefresh = false;
                page++;
                getJobs(isFirst);
            }
        });
    }

    //关闭下拉刷新
    private void closePullTo() {
        pullToBothLayout.finishRefresh();
        pullToBothLayout.finishLoadMore();
    }

    private void initSelectionRecommendation() {
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        if (part2JobAdapter == null) {
            part2JobAdapter = new Part2PublicAdapter(getActivity(), list_jobs);
        }
        recyclerView1.setHasFixedSize(true);
        recyclerView1.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator1 = recyclerView1.getItemAnimator();
        if (animator1 instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator1).setSupportsChangeAnimations(false);
        }
        recyclerView1.setLayoutManager(manager1);
        recyclerView1.setAdapter(part2JobAdapter);
        part2JobAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(), PartDetailActivity.class).putExtra("jobId", list_jobs.get(position).getJobId()));
            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        if (part2MsgAdapter == null) {
            part2MsgAdapter = new Part2MsgAdapter(getActivity(), list);
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(part2MsgAdapter);
        part2MsgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(getActivity(), PartDetailActivity.class).putExtra("jobId", list.get(position).getJobId()));
            }
        });
    }


    //初始化 筛选东西
    private void initScreenView() {
        screenSexAdapter = new ScreenSexAdapter(getActivity(), sexArray);
        screenAccountAdapter = new ScreenAccountAdapter(getActivity(), accountArray);
        screenWeekAdapter = new ScreenWeekAdapter(getActivity(), weekArray);
        RecyclerView.ItemAnimator animator = recycle_1.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);
        recycle_1.setHasFixedSize(true);
        recycle_1.setLayoutManager(layoutManager);
        GridItemDecoration divider = new GridItemDecoration.Builder(Objects.requireNonNull(getActivity()))
                .setHorizontalSpan(R.dimen.dp9)
                .setVerticalSpan(R.dimen.dp9)
                .setColorResource(R.color.whiteffffff)
                .setShowLastLine(false)
                .build();
        recycle_1.addItemDecoration(divider);
        recycle_1.setAdapter(screenSexAdapter);

        RecyclerView.ItemAnimator animator1 = recycle_2.getItemAnimator();
        if (animator1 instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator1).setSupportsChangeAnimations(false);
        }
        GridLayoutManager layoutManager1 = new GridLayoutManager(getActivity(), 4);
        recycle_2.setHasFixedSize(true);
        recycle_2.setLayoutManager(layoutManager1);
        recycle_2.addItemDecoration(divider);
        recycle_2.setAdapter(screenAccountAdapter);


        RecyclerView.ItemAnimator animator2 = recycle_3.getItemAnimator();
        if (animator2 instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator2).setSupportsChangeAnimations(false);
        }
        GridLayoutManager layoutManager2 = new GridLayoutManager(getActivity(), 4);
        recycle_3.setHasFixedSize(true);
        recycle_3.setLayoutManager(layoutManager2);
        recycle_3.addItemDecoration(divider);
        recycle_3.setAdapter(screenWeekAdapter);
    }

    //初始化数据
    private void initScreenData() {
        NoValidationTask.getApiService().getSiftList().enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                JSONArray endType = jsonObject.getJSONArray("endtype");
                JSONArray sex = jsonObject.getJSONArray("sex");
                JSONArray settle = jsonObject.getJSONArray("settle");
                if (endType.size() > 0 && sex.size() > 0 && settle.size() > 0) {
                    sexArray.clear();
                    accountArray.clear();
                    weekArray.clear();
                    for (int i = 0; i < sex.size(); i++) {
                        PartSiftEntity screenEntity = new PartSiftEntity();
                        screenEntity.setNameValue(JSON.parseObject(JSONObject.toJSONString(sex.get(i))).getString("nameValue"));
                        screenEntity.setDelFlag(JSON.parseObject(JSONObject.toJSONString(sex.get(i))).getInteger("delFlag") + "");
                        screenEntity.setNameIndex(JSON.parseObject(JSONObject.toJSONString(sex.get(i))).getInteger("nameIndex") + "");
                        screenEntity.setType(JSON.parseObject(JSONObject.toJSONString(sex.get(i))).getString("type"));
                        screenEntity.setTypeId(JSON.parseObject(JSONObject.toJSONString(sex.get(i))).getInteger("id") + "");

                        sexArray.add(screenEntity);
                    }
                    for (int i = 0; i < settle.size(); i++) {
                        PartSiftEntity screenEntity = new PartSiftEntity();
                        screenEntity.setNameValue(JSON.parseObject(JSONObject.toJSONString(settle.get(i))).getString("nameValue"));
                        screenEntity.setDelFlag(JSON.parseObject(JSONObject.toJSONString(settle.get(i))).getInteger("delFlag") + "");
                        screenEntity.setNameIndex(JSON.parseObject(JSONObject.toJSONString(settle.get(i))).getInteger("nameIndex") + "");
                        screenEntity.setType(JSON.parseObject(JSONObject.toJSONString(settle.get(i))).getString("type"));
                        screenEntity.setTypeId(JSON.parseObject(JSONObject.toJSONString(settle.get(i))).getInteger("id") + "");

                        accountArray.add(screenEntity);
                    }
                    for (int i = 0; i < endType.size(); i++) {
                        PartSiftEntity screenEntity = new PartSiftEntity();
                        screenEntity.setNameValue(JSON.parseObject(JSONObject.toJSONString(endType.get(i))).getString("nameValue"));
                        screenEntity.setDelFlag(JSON.parseObject(JSONObject.toJSONString(endType.get(i))).getInteger("delFlag") + "");
                        screenEntity.setNameIndex(JSON.parseObject(JSONObject.toJSONString(endType.get(i))).getInteger("nameIndex") + "");
                        screenEntity.setType(JSON.parseObject(JSONObject.toJSONString(endType.get(i))).getString("type"));
                        screenEntity.setTypeId(JSON.parseObject(JSONObject.toJSONString(endType.get(i))).getInteger("id") + "");
                        weekArray.add(screenEntity);
                    }
                    screenSexAdapter.notifyDataSetChanged();
                    screenAccountAdapter.notifyDataSetChanged();
                    screenWeekAdapter.notifyDataSetChanged();

                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    // 获取带背景图的list列表
    private void getJobsRecome() {
        NoValidationTask.getApiService().getJobsRecome().enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        Part2MsgEntity part2MsgEntity = new Part2MsgEntity();
                        part2MsgEntity.setTitle(jsonArray.getJSONObject(i).getString("jobTitle"));
                        part2MsgEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                        part2MsgEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                        part2MsgEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                        part2MsgEntity.setImgUrl(jsonArray.getJSONObject(i).getString("imgUrl"));
                        list.add(part2MsgEntity);
                    }
                }
                part2MsgAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }


    //获取职位列表 筛选用的
    private void getJobs(boolean isFirst) {
        String sex;
        String account;
        String week;
        if (isFirst) {
            sex = null;
            account = null;
            week = null;
        } else {
            if (sexSelected == -1) {
                sex = sexArray.get(0).getNameIndex();
            } else {
                sex = sexArray.get(sexSelected).getNameIndex();
            }
            if (accountSelected == -1) {
                account = accountArray.get(0).getNameIndex();
            } else {
                account = accountArray.get(accountSelected).getNameIndex();
            }
            if (weekSelected == -1) {
                week = weekArray.get(0).getNameIndex();
            } else {
                week = weekArray.get(weekSelected).getNameIndex();
            }

        }
        NoValidationTask.getApiService().getJXJobs(page, sex, account, week).enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    if (isRefresh) {
                        list_jobs.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list_jobs.add(part2JobEntity);
                        }

                    } else {//上拉加载
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Part2JobEntity part2JobEntity = new Part2JobEntity();
                            part2JobEntity.setEducation(jsonArray.getJSONObject(i).getString("eduRequire"));
                            part2JobEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            part2JobEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            part2JobEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            part2JobEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            part2JobEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            part2JobEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            part2JobEntity.setYear(jsonArray.getJSONObject(i).getString("expRequire"));
                            list_jobs.add(part2JobEntity);
                        }
                    }
                }
                part2JobAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {
                closePullTo();
            }
        });
    }
}
